/*
 * @Author: 悦者生存 1002783067@qq.com
 * @Date: 2023-03-11 14:57:22
 * @LastEditors: 悦者生存 1002783067@qq.com
 * @LastEditTime: 2023-04-13 21:11:20
 * @FilePath: /koa2-ts-template/src/common/utils/file.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import koa from 'koa';
import path from 'path';
import fs from 'fs-extra';

const uploadUrl = '/public/upload';
interface File {
  filepath: fs.PathLike;
  originalFilename: string;
}

export const uploadFile = (file: File, ctx: koa.Context) => {
  try {
    const fileReader = fs.createReadStream(file.filepath);
    const fileDir = path.join(__dirname, '../../public/upload/');
    const filePath = `${fileDir}${file.originalFilename}`;
    const writeStream = fs.createWriteStream(filePath); // 这里会自动创建文件，因为createWriteStream的flags为w，w为写入，如果文件不存在则创建文件
    fileReader.pipe(writeStream); //这里返回的不是promise，不是很友好
    const url = `${uploadUrl}${file.originalFilename}`;
    ctx.success({ url }, '文件上传成功', true);
  } catch (error) {
    console.log(error);
    throw new Error('文件上传失败');
  }
};
